package com.xiaobai.design_pattern.proxy;

import org.junit.jupiter.api.Test;
import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 * @author wangtw
 * @date 2023/12/1 23:21
 * @description 代理模式测试类
 */
public class ClientDemo {

    @Test
    public void test() {
        IGamePlayer player = new GamePlayer("芈月");
        IGamePlayer proxy = new GamePlayerProxy(player);
        proxy.killBoss();
        proxy.upGrade();
    }

    @Test
    public void jdkProxyTest() {
        //生成代理类文件 在根目录的同级目录，com下
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        IGamePlayer player = new GamePlayer("澜");
        Class<? extends IGamePlayer> playerClass = player.getClass();
        //代理类 实现需要实现InvocationHandler接口，重写invoke方法 传入业务实现类对象
        JdkGamePlayerProxy jdkGamePlayerProxy = new JdkGamePlayerProxy(player);

        // 创建代理类对象
        /**
         *
         loader – the class loader to define the proxy class
         interfaces – the list of interfaces for the proxy class to implement
         h – the invocation handler to dispatch method invocations to
         */
        IGamePlayer proxy = (IGamePlayer) Proxy.newProxyInstance(playerClass.getClassLoader(),
                playerClass.getInterfaces(), jdkGamePlayerProxy);
        System.out.println(proxy.getClass());
        proxy.killBoss();
        proxy.upGrade();
    }

    @Test
    public void cglibProxyTest() {
        IGamePlayer gamePlayer = new GamePlayer("亚瑟");

        // 对目标方法进行增强
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(IGamePlayer.class); // 设置要代理的父类
        enhancer.setCallback(new CglibGamePlayerProxy(gamePlayer)); // 设置回调的拦截器

        IGamePlayer proxy = (IGamePlayer) enhancer.create(); // 创建代理对象

        proxy.killBoss();
        proxy.upGrade();
    }
}
